<template>
  <div class="event-list-page">
    <div class="page-header">
      <h1>事件列表</h1>
      <n-space>
        <n-button
          v-if="hasDietTrackingEvents"
          @click="showExportDialog = true"
          quaternary
        >
          <n-icon :size="16">
            <Download />
          </n-icon>
          导出饮食记录
        </n-button>
        <n-button type="primary" @click="$router.push('/events/create')">
          <n-icon :size="16">
            <Add />
          </n-icon>
          创建事件
        </n-button>
      </n-space>
    </div>
    
    <div class="page-content">
      <div class="filters">
        <n-space>
          <n-date-picker
            v-model:value="dateRange"
            type="daterange"
            placeholder="选择日期范围"
            @update:value="handleDateRangeChange"
          />
          <n-select
            v-model:value="selectedEventType"
            placeholder="事件类型"
            :options="eventTypeOptions"
            clearable
            @update:value="handleEventTypeChange"
          />
        </n-space>
      </div>
      
      <div class="events-container">
        <n-spin :show="eventsStore.loading">
          <div v-if="filteredEvents.length === 0" class="empty-state">
            <n-icon :size="64" color="#ccc">
              <Calendar />
            </n-icon>
            <p>暂无事件</p>
          </div>
          
          <div v-else class="events-grid">
            <div
              v-for="event in filteredEvents"
              :key="event.id"
              class="event-card"
              @click="handleEventClick(event)"
            >
              <div class="event-header">
                <div class="event-type-indicator" :style="{ backgroundColor: getEventColor(event) }"></div>
                <div class="event-title">{{ event.title }}</div>
                <n-button
                  size="small"
                  :type="event.is_completed ? 'success' : 'default'"
                  @click.stop="toggleEventCompletion(event)"
                >
                  <n-icon :size="16">
                    <Checkmark v-if="event.is_completed" />
                    <Ellipse v-else />
                  </n-icon>
                </n-button>
              </div>
              
              <div class="event-content">
                <div class="event-date">
                  {{ formatDate(event.start_date, 'MM月DD日') }}
                  <span v-if="event.start_time">{{ formatTime(event.start_time) }}</span>
                </div>
                <div v-if="event.description" class="event-description">
                  {{ event.description }}
                </div>
              </div>
            </div>
          </div>
        </n-spin>
      </div>
    </div>

    <!-- 导出对话框 -->
    <DietExportDialog
      :is-open="showExportDialog"
      :events="eventsStore.events.map(e => ({
        ...e,
        recurrence_pattern: e.recurrence_pattern ? {
          ...e.recurrence_pattern,
          days_of_week: e.recurrence_pattern.days_of_week ? [...e.recurrence_pattern.days_of_week] : undefined
        } : undefined,
        event_type: e.event_type ? {
          ...e.event_type,
          form_config: {
            ...e.event_type.form_config,
            fields: e.event_type.form_config.fields.map(field => ({
              ...field,
              options: field.options ? [...field.options] : undefined
            }))
          }
        } : undefined
      }))"
      @close="showExportDialog = false"
      @exported="handleExported"
    />
  </div>
</template>

<script setup lang="ts">
import { Add, Calendar, Checkmark, Ellipse, Download } from '@vicons/ionicons5'
import { useEventsStore } from '@/stores/events'
import { formatDate, formatTime } from '@/utils/date'
import DietExportDialog from '@/components/DietExportDialog.vue'
// import type { Event } from '@/types'

const router = useRouter()
const eventsStore = useEventsStore()

// 筛选条件
const dateRange = ref<[number, number] | null>(null)
const selectedEventType = ref<number | null>(null)

// 导出对话框状态
const showExportDialog = ref(false)

// 事件类型选项
const eventTypeOptions = computed(() => {
  return eventsStore.eventTypes.map((type: any) => ({
    label: type.name,
    value: type.id
  }))
})

// 检查是否有饮食跟踪事件
const hasDietTrackingEvents = computed(() => {
  return eventsStore.events.some(event =>
    event.event_type?.name === '饮食跟踪' && event.extra_data?.foods_intake
  )
})

// 筛选后的事件
const filteredEvents = computed(() => {
  let events = eventsStore.events

  // 按日期筛选
  if (dateRange.value) {
    const [start, end] = dateRange.value
    const startDate = formatDate(new Date(start), 'YYYY-MM-DD')
    const endDate = formatDate(new Date(end), 'YYYY-MM-DD')

    events = events.filter(event => {
      return event.start_date >= startDate && event.start_date <= endDate
    })
  }

  // 按事件类型筛选
  if (selectedEventType.value) {
    events = events.filter(event => event.event_type_id === selectedEventType.value)
  }

  return [...events].sort((a, b) => new Date(b.start_date).getTime() - new Date(a.start_date).getTime())
})

// 获取事件颜色
const getEventColor = (event: any) => {
  const eventType = eventsStore.getEventType(event.event_type_id)
  return eventType?.color || '#2196F3'
}

// 处理日期范围变化
const handleDateRangeChange = (value: [number, number] | null) => {
  dateRange.value = value
}

// 处理事件类型变化
const handleEventTypeChange = (value: number | null) => {
  selectedEventType.value = value
}

// 处理事件点击
const handleEventClick = (event: any) => {
  router.push(`/events/${event.id}`)
}

// 切换事件完成状态
const toggleEventCompletion = async (event: any) => {
  await eventsStore.toggleEventCompletion(event.id, !event.is_completed)
}

// 处理导出完成
const handleExported = (filename: string) => {
  window.$message?.success(`导出成功: ${filename}`)
}

// 初始化
onMounted(async () => {
  await eventsStore.init()
})
</script>

<style scoped>
.event-list-page {
  padding: 24px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.page-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.filters {
  margin-bottom: 24px;
}

.events-container {
  flex: 1;
  overflow-y: auto;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-state p {
  margin-top: 16px;
  color: #666;
  font-size: 16px;
}

.events-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.event-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.2s ease;
}

.event-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.event-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.event-type-indicator {
  width: 4px;
  height: 24px;
  border-radius: 2px;
}

.event-title {
  flex: 1;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.event-content {
  margin-left: 16px;
}

.event-date {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.event-description {
  font-size: 14px;
  color: #999;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

@media (max-width: 768px) {
  .event-list-page {
    padding: 16px;
  }
  
  .events-grid {
    grid-template-columns: 1fr;
  }
}
</style>
